﻿using System;
using System.Collections;
using System.Collections.Generic;
using NHibernate;
using NHibernate.Criterion;
using ScrumBox.Model;

namespace ScrumBox.DataAccess.Repositories
{
    public class ProjectRepository : RepositoryBase, IProjectRepository
    {
        public ProjectRepository(ISessionBuilder sessionFactory)
            : base(sessionFactory)
        {
        }

        #region IProjectRepository Members

        public IList<Project> GetAllProjects()
        {
            var query = getSession().CreateQuery("from Project");
            return query.List<Project>();
        }

        public Project GetById(Guid id)
        {
            return getSession().Get<Project>(id);
        }

        public Project GetByKey(string key)
        {
            var criteria = getSession().CreateCriteria(typeof(Project));
            criteria.Add(Restrictions.Eq("Key", key));
            
            return criteria.UniqueResult<Project>();
        }

        public void Save(Project project)
        {
            var session = getSession();
            session.SaveOrUpdate(project);
            session.Flush();
        }

        public bool ProjectExists(string projectName, string projectKey)
        {
            var session = getSession();
            var query =
                session.CreateQuery("select count(*) from Project c where c.Name like :name OR c.Key like :key");
            query.SetString("name", projectName);
            query.SetString("key", projectKey);
            query.SetMaxResults(1);
            return (long) query.UniqueResult() > 0;
        }

        #endregion
    }
}